import React, { useState, useEffect, useCallback, useRef } from "react";
import { Plus, Trash2 } from "lucide-react";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";

const StringArrayEditor = ({ title, items = [], onUpdate, placeholder }) => {
  // 使用带有唯一ID的内部状态管理输入项
  const [internalItems, setInternalItems] = useState([]);
  const addButtonRef = useRef(null);

  // 初始化：将传入的items转换为带ID的格式
  useEffect(() => {
    if (items && items.length > 0) {
      // 确保初始化时生成唯一且稳定的ID
      const initializedItems = items.map((item, index) => ({
        id: `initial-item-${index}`,
        value: item
      }));
      setInternalItems(initializedItems);
    } else {
      setInternalItems([]);
    }
  }, [items]);

  // 当内部状态变化时通知父组件
  useEffect(() => {
    if (onUpdate) {
      const values = internalItems.map(item => item.value).filter(Boolean);
      onUpdate(values);
    }
  }, [internalItems, onUpdate]);

  // 添加新条目 - 简化状态更新逻辑
  const handleAddItem = useCallback(() => {
    console.log('3333');
    // 使用更可靠的ID生成方式
    const newId = `item-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
    const newItem = {
      id: newId,
      value: ""
    };
    
    // 使用函数式更新确保获取最新状态
    setInternalItems(prevItems => [...prevItems, newItem]);
  }, []);

  // 更新条目内容
  const handleUpdateItem = useCallback((id, value) => {
    setInternalItems(prevItems => 
      prevItems.map(item => 
        item.id === id ? { ...item, value } : item
      )
    );
  }, []);

  // 删除条目
  const handleRemoveItem = useCallback((id) => {
    setInternalItems(prevItems => prevItems.filter(item => item.id !== id));
  }, []);

  return (
    <div className="space-y-3 p-4 border rounded-lg shadow-sm transition-all hover:shadow-md">
      <div className="flex items-center justify-between">
        <h4 className="font-medium text-lg text-gray-800">{title}</h4>
        <Button
          ref={addButtonRef}
          variant="outline"
          size="sm"
          onClick={handleAddItem}
          className="transition-all hover:bg-blue-50 hover:text-blue-600"
          aria-label="添加新条目"
        >
          <Plus className="w-4 h-4 mr-2" /> 添加条目
        </Button>
      </div>

      <div className="space-y-2">
        {internalItems.length > 0 ? (
          <div className="space-y-3">
            {internalItems.map((item) => (
              <div
                key={item.id} // 使用稳定的唯一ID作为key
                className="flex gap-2 items-center group"
              >
                <Input
                  value={item.value || ""}
                  onChange={(e) => handleUpdateItem(item.id, e.target.value)}
                  placeholder={placeholder || `请输入${title.toLowerCase()}内容`}
                  className="flex-1 transition-all focus:ring-2 focus:ring-blue-500"
                  // 仅在新添加的空项上设置自动聚焦
                  autoFocus={item.value === "" && internalItems[internalItems.length - 1].id === item.id}
                />
                <Button
                  variant="ghost"
                  size="icon"
                  onClick={() => handleRemoveItem(item.id)}
                  className="text-gray-400 hover:text-red-500 opacity-70 group-hover:opacity-100 transition-all"
                  aria-label="删除条目"
                >
                  <Trash2 className="w-4 h-4" />
                </Button>
              </div>
            ))}
          </div>
        ) : (
          <div className="text-center py-6 text-gray-500 border border-dashed rounded-md bg-gray-50">
            <p className="text-sm">
              暂无{title.toLowerCase()}，点击"添加条目"添加。
            </p>
          </div>
        )}
      </div>
    </div>
  );
};

export default StringArrayEditor;
    